<?php

namespace app\home\controller;

use think\Controller;

use think\Input;

use think\Db;

use think\Request;

use think\Session;

class Car extends Controller{
	
	
	//购物车
	public function index(){
		
		$car = session('car');
		
		$this->assign('car',$car);
	return view();	
		
	}
	
	
	
	
	
	
	
	
	
	
	//添加购物车
	public function add(){
		
		$data = input('post.');
		
		$car = session('car');
		if($car){
			//查询购物车中是否包含该商品信息
			foreach($car as $value){
				if($value['id'] == $data['good']['id']){
					
					return json(['msg'=>"购物内商品已存在"]);
				}
				
			}
			
			
			
			array_push($car,$data['good']);
			
		
		}else{
			$car =[];
			array_push($car,$data['good']);
		
		}
		
		//更新购物车
		session('car',$car);
		return json(['msg'=>'加入购物车成功']);
	
		
	}
	
	
	//提交订单
	public function doorder(){
		$data = input('post.');
		
		//创建订单
		//生成唯一订单号
		$data['ordernum'] = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
		//生成订单时间
		$data['addtime'] = date('Y-m-d H:i:s',time());
		
	     $data['goods'] = json_encode($data['goods']);
		

		
		//插入订单
	    $order = db('ordermanger')->insertGetId($data);
		
		if($order){
			
//			插入成功返回id
			return ['code'=>200,'orderId'=>$order];
		}else{
			
			return ['code'=>400,'msg'=>'网络异常'];
		}
		

	}
	
	
	//生成订单
	public function orderpay($orderId){
		
		
//		查询订单信息
       $data = db('ordermanger')->where("id=".$orderId)->find();
      

      $this->assign('data',$data);
      
      $this->assign('goods',json_decode($data['goods'],true));
		
		return view();
	}
	
	
	
}

